package com.yanqu.road.server.manager.activity.biaoju;

import com.yanqu.road.entity.activity.biaoju.CrossBiaoJuBestEscortData;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.date.DateHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 每轮的优质镖
 */
public class CrossBiaoJuBestEscortRoundInfo {
    private int round;
    /**
     * key 品质
     */
    private Map<Integer, CrossBiaoJuBestEscortData> bestEscortDataMap = new ConcurrentHashMap<>();

    public CrossBiaoJuBestEscortRoundInfo(int round) {
        this.round = round;
    }

    public int getRound() {
        return round;
    }

    public void addDbBestEscortData(CrossBiaoJuBestEscortData bestEscortData) {
        bestEscortDataMap.put(bestEscortData.getQuality(), bestEscortData);
    }

    public void addNewBestEscortData(CrossBiaoJuBestEscortData bestEscortData) {
        int quality = bestEscortData.getQuality();
        bestEscortDataMap.put(quality, bestEscortData);
    }

    public int getRemainBestEscortCount() {
        int count = 0;
        for (CrossBiaoJuBestEscortData bestEscortData : bestEscortDataMap.values()) {
            count += bestEscortData.getRemainNum();
        }
        return count;
    }

    public List<CrossBiaoJuBestEscortData> getBestEscortList() {
        List<CrossBiaoJuBestEscortData> list = new ArrayList<>(bestEscortDataMap.values());
        return list;
    }

    /**
     * 随机取出一个优质镖
     *
     * @param quality
     * @return
     */
    public synchronized CrossBiaoJuBestEscortData randomPopOnceBestEscort(int quality, long userId) {
        CrossBiaoJuBestEscortData bestEscortData = bestEscortDataMap.get(quality);
        if (bestEscortData == null) {
            return null;
        }
        if (bestEscortData.getRemainNum() <= 0){
            return null;
        }
        bestEscortData.setTakeUserId(userId);
        bestEscortData.setTakeTime(DateHelper.getCurrentTime());
        bestEscortData.setRemainNum(bestEscortData.getRemainNum() - 1);
        return bestEscortData;
    }

    /**
     * 返还优质镖
     *
     * @param bestEscortUniqueId
     */
    public synchronized void backBestEscort(int bestEscortUniqueId) {
        for (CrossBiaoJuBestEscortData bestEscortData : bestEscortDataMap.values()) {
            if (bestEscortData.getUniqueId() == bestEscortUniqueId) {
                bestEscortData.setRemainNum(bestEscortData.getRemainNum() + 1);
                break;
            }
        }
    }
}
